#!/bin/bash

# 设置版本号
current_version=20250916

# 更新脚本函数
update_script() {
    update_url="https://gitee.com/dudu1luchang/dudu/raw/master/dudu.sh"
    tmp_file=$(mktemp)
    if ! curl -s --connect-timeout 10 -o "$tmp_file" -H "Cache-Control: no-cache" "$update_url"; then
        echo "无法连接到更新服务器，跳过检查。"
        rm -f "$tmp_file"
        return 1
    fi
    latest_version=$(grep -oP 'current_version=([0-9]+)' "$tmp_file" | cut -d '=' -f2)
    if [[ -z "$latest_version" || ! "$latest_version" =~ ^[0-9]+$ ]]; then
        echo "无法解析远程版本号，跳过更新。"
        rm -f "$tmp_file"
        return 1
    fi
    if [[ "$latest_version" -gt "$current_version" ]]; then
        echo -e "\033[31m发现新版本！当前版本：$current_version，最新版本：$latest_version\033[0m"
        echo "正在更新..."
        mv "$tmp_file" "$0" && chmod +x "$0"
        echo "更新完成，重新启动脚本..."
        exec "$0" "$@"
    else
        echo "当前脚本已是最新版本。"
        rm -f "$tmp_file"
    fi
}

# 查询 CPU 温度和功耗函数
query_cpu_stats() {
    if ! command -v sensors &> /dev/null; then
        echo "sensors 未安装，正在安装..."
        sudo apt-get update -y
        sudo apt-get install -y lm-sensors
    fi
    if ! command -v powerstat &> /dev/null; then
        echo "powerstat 未安装，正在安装..."
        sudo apt-get update -y
        sudo apt-get install -y powerstat
    fi
    echo "获取 CPU 温度信息..."
    cpu_temps=$(sensors | grep -i 'Tctl' | awk '{print $2}' | sed 's/+//g' | sed 's/°C//g')
    if [ -z "$cpu_temps" ]; then
        echo "无法获取 CPU 温度信息"
    else
        cpu_count=1
        for temp in $cpu_temps; do
            echo "CPU$cpu_count 温度：$temp°C"
            ((cpu_count++))
        done
    fi
    echo "查询功耗信息..."
    powerstat_output=$(timeout 5 powerstat -z -R 1 60 2>/dev/null)
    if [ -z "$powerstat_output" ]; then
        echo "无法获取 powerstat 输出，检查命令或权限。"
        return
    fi
    power=$(echo "$powerstat_output" | grep -i "CPU:" | awk '{print $2 " W"}')
    echo "功耗：$power"
}

# 安装服务端
install_server() {
    echo "安装服务端..."
    sudo mkdir -p /os
    sudo curl -s -o /os/server.py https://gitee.com/dudu1luchang/dudu/raw/master/server.py
    sudo chmod +x /os/server.py
    # 启动服务端 screen
    if ! command -v screen &>/dev/null; then
        sudo apt-get update -y && sudo apt-get install -y screen
    fi
    screen -dmS miner_server python3 /os/server.py
    echo "服务端已安装并在 screen 中启动。"
}

# 安装客户端
install_client() {
    echo "安装客户端..."
    USERNAME=$(whoami)
    mkdir -p /os-user
    curl -s -o /os-user/report.sh https://gitee.com/dudu1luchang/dudu/raw/master/report.sh
    chmod +x /os-user/report.sh

    # 询问矿机名称
    echo "请输入矿机名称(建议名称为统一开头以便之后账号划分机子, 如 du-01, du-7945hx, du-Abc):"
    read -p "矿机名称: " MINER_NAME
    if [ -z "$MINER_NAME" ]; then
        echo "未输入矿机名称，使用默认 $(hostname)"
        MINER_NAME=$(hostname)
    fi

    # 替换 report.sh 里的 $(hostname)
    sed -i "s/\$(hostname)/$MINER_NAME/g" /os-user/report.sh

    echo "矿机名称已设置为：$MINER_NAME"

    # 配置 sudo 权限
    if ! grep -q "$USERNAME ALL=(ALL) NOPASSWD: /usr/bin/pkill, /usr/bin/screen" /etc/sudoers; then
        echo "$USERNAME ALL=(ALL) NOPASSWD: /usr/bin/pkill, /usr/bin/screen, /qubic/xmrig, /qubic/*" | sudo EDITOR='tee -a' visudo
    fi

    # 配置 crontab，避免重复添加
    if ! crontab -l 2>/dev/null | grep -q "/os-user/report.sh"; then
        (crontab -l 2>/dev/null; echo "*/2 * * * * /os-user/report.sh") | crontab -
        echo "crontab 已添加，每两分钟启动 /os-user/report.sh"
    else
        echo "crontab 中已存在 /os-user/report.sh，跳过添加"
    fi

    echo "客户端安装完成。"
}


# 安装矿机监测系统
install_miner_system() {
    echo "选择安装类型:"
    echo "1. 安装服务端（不可用，请咨询 嘟·叫兽）"
    echo "2. 安装客户端"
    read -p "请输入选项 (1/2): " sub_option
    case $sub_option in
#        1) install_server ;;
        2) install_client ;;
        *) echo "无效选项，返回主菜单"; sleep 2 ;;
    esac
}

# 主菜单
main_menu() {
    while true; do
        clear
        echo "=========2025一定暴富========="
        echo "当前版本：$current_version"
        echo "有问题请联系：du.叫兽（微信号duduyiluchang）"
        echo "请选择项目:"
        echo "--------------------项目--------------------"
        echo "1. 查询 CPU 温度和功耗"
        echo "2. 安装矿机监测系统"
        echo "101. 双挖xmr+tair"
        echo "102. 单挖zeph"
        echo "103. 单挖sal"
        echo "0. 退出脚本exit"
        read -p "请输入选项: " OPTION

        case $OPTION in
            1) query_cpu_stats ;;
            2) install_miner_system ;;
            101) wget -O choose_xmr.sh https://gitee.com/dudu1luchang/dudu/raw/master/choose_xmr.sh && chmod +x choose_xmr.sh && bash choose_xmr.sh ;;
            102) wget -O choose_zeph.sh https://gitee.com/dudu1luchang/dudu/raw/master/choose_zeph.sh && chmod +x choose_zeph.sh && bash choose_zeph.sh ;;
            103) wget -O choose_sal.sh https://gitee.com/dudu1luchang/dudu/raw/master/choose_sal.sh && chmod +x choose_sal.sh && bash choose_sal.sh ;;
            0) echo "退出脚本。"; exit 0 ;;
            *) echo "无效选项，请重新输入。"; sleep 3 ;;
        esac
        echo "按任意键返回主菜单..."
        read -n 1
    done
}

# 检查更新
update_script

# 显示主菜单
main_menu
